<template>
  <el-form ref="deptForm" label-width="120px" :rules="rules" :model="form">
    <el-form-item label="部门名称" prop="name">
      <el-input
        v-model="form.name"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input
        v-model="form.code"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width: 80%" placeholder="请选择">
        <el-option
          v-for="item in list"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input
        v-model="form.introduce"
        style="width: 80%"
        placeholder="1-300个字符"
        type="textarea"
        :rows="3"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeesSimples } from '@/api/employees'
import {
  addDepartment,
  getDepartmentDetails,
  editDepartment
} from '@/api/departments'
export default {
  props: {
    originList: {
      type: Array,
      required: true
    },
    id: {
      type: String,
      required: true
    },
    edit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    const validCode = (rule, value, callback) => {
      // 验证用户输入的value值,在整个项目中的编码是否已经存在
      //  - 获取整个部门的编码,编码的数组
      console.log('this.originList', this.originList)
      let existCodeList = this.originList.map((item) => item.code)
      console.log('existCodeList', existCodeList)
      // 如果是编辑的状态,当前编辑的部门的编码从存在的数组中移除,然后再判断
      if (this.edit) {
        existCodeList = this.originList.filter(item => item.id !== this.id).map(item => item.code)
      }
      // 判断当前value值，是否在数组中存在
      if (existCodeList.includes(value)) {
        callback(new Error(`该部门编码${value}已存在,请换一个编码`))
      } else {
        // 不存在,校验通过
        callback()
      }
    }
    // 定义一个校验规则函数,校验部门名称同级不能重复
    const validName = (rule, value, callback) => {
      // 被占用的列表 --> 当前点击的部门的子部门
      let existNameList = this.originList.filter(item => item.pid === this.id).map(item => item.name)
      console.log('existNameList', existNameList)
      if (this.edit) {
        const pid = this.originList.find(item => item.id === this.id).pid
        // console.log('this.originList.find(item => item.id === this.id).pid', pid)
        const brother = this.originList.filter(item => item.pid === pid)
        // console.log('this.originList.filter(item => item.pid === pid)', brother)
        existNameList = brother.filter(item => item.id !== this.id).map(item => item.name)
        // console.log('brother.filter(item => item.id !== this.id).map(item => item.name)', existNameList)
      }
      // 判断当前用户输入的value,在被占用列表中是否存在
      if (existNameList.includes(value)) {
        // 存在校验失败
        callback(new Error(`该部门名称${value}已经存在,不能重复!`))
      } else {
        // 不存在 校验成功
        callback()
      }
    }
    return {
      list: [],
      // 根据接口文档命名
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      // 验证规则对象
      rules: {
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1~50的部门名称', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '请输入1~50的部门编码', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '部门负责人不能为空', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '请输入1~300的部门编码',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  // 侦听器组件内props中属性或者data中属性的变化
  // watch: {
  //   id: function(new_val, old_val) {
  //     console.log('new_val', new_val)
  //     console.log('old_val', old_val)
  //     // 解决数据不更新的方式三
  //     this.loadDepartmentDetails()
  //   }
  // },
  created() {
    this.loadEmployeeSimples()
    if (this.edit) {
      this.loadDepartmentDetails()
    }
  },
  methods: {
    // 在子组件中定义重置表单的方法
    resetForm() {
      this.$refs.deptForm.resetFields()
      this.form = {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      }
    },
    // 根据id加载部门详情数据,填充到表单中
    async loadDepartmentDetails() {
      try {
        const { data: res } = await getDepartmentDetails(this.id)
        console.log('loadDepartmentDetails', res)
        // 填充表单
        this.form = res
      } catch (error) {
        console.log('loadDepartmentDetails', error)
      }
    },
    // 实现编辑部门
    async doEdit() {
      try {
        const { res } = await editDepartment(this.form)
        console.log('doEdit成功', res)
        this.$emit('success')
      } catch (error) {
        console.log('doEdit失败', error)
      }
    },
    // 实现新增子部门
    async doAdd() {
      try {
        // 发送请求 this.form中缺少pid ,如何获取到pid???
        const { data: res } = await addDepartment({
          pid: this.id,
          ...this.form
        })
        console.log('doAdd', res)
        // 子传父
        this.$emit('success')
      } catch (error) {
        console.log('doAdd', error)
      }
    },
    // 确认提交
    async hSubmit() {
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return // 校验失败
        this.edit ? this.doEdit() : this.doAdd()
      })
    },
    // 获取表单数据
    async loadEmployeeSimples() {
      try {
        const { data: res } = await getEmployeesSimples(this.list)
        console.log('loadEmployeeSimples', res)
        this.list = res
      } catch (error) {
        console.log('loadEmployeeSimples发送请求错误', error)
      }
    },
    // 取消按钮
    hCancel() {
      // 关闭弹层
      this.$emit('close')
    }
  }
}
</script>

<style>
</style>
